import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:magic_car/common/global.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/user/agenterror.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:magic_car/main.dart';

class LoginPage extends StatefulWidget {
  //LoginPage({Key key, this.title,this.role}) : super(key: key);

  //final String title;
  final String role;

  LoginPage(this.role);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.role);
}

class _MyHomePageState extends State<LoginPage> {
  bool _phoneState, _pwdState = false;
  String _checkStr;
  String roles;
  _MyHomePageState(this.roles);

  TextEditingController _phonecontroller = new TextEditingController();
  TextEditingController _pwdcontroller = new TextEditingController();

  void _checkPhone() {
    if (_phonecontroller.text.isNotEmpty) {
      _phoneState = true;
    } else {
      _phoneState = false;
    }
  }

  void _checkPwd() {
    if (_pwdcontroller.text.isNotEmpty &&
        _pwdcontroller.text.trim().length >= 6) {
      _pwdState = true;
    } else {
      _pwdState = false;
    }
  }

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
  }

  login() async {
    FocusScope.of(context).requestFocus(FocusNode());
    Map<String, String> map = new Map();
    map["mobile"] = _phonecontroller.text.trim();
    map["password"] = _pwdcontroller.text.trim();
    SharedPreferences pref = await SharedPreferences.getInstance();
    if (pref.getString('registeid') != null) {
      map["registed_Id"] = pref.getString('registeid');
    }

    String api = HttpHelper.API_UserLog;
    if (pref.getString('role') == "0") {
      //车商
      api = HttpHelper.API_LoginBusiness;
    }

    HttpHelper.postUrl(
        api,
        context,
        (data) async {
          print(data);
          if (data != null) {
            print(data);
            Toast.show(data["msg"], context);

            if (data["code"].toString() == "1") {
              pref.setString('islogin', '1');
              pref.setString('role', roles);
              pref.setString("uid", data["info"]["id"].toString());

              pref.setString("isshenhe", '0');

              if (roles == "0") {
                if (data["info"]["is_bussiness"].toString() == "1") {
                  //设置经纪人缓存识别
                  pref.setString('agent', "0");
                } else {
                  pref.setString('agent', "1");
                }
              }

              // pref.setStringList('userinfo', data["info"]);
              Navigator.of(context).pushAndRemoveUntil(
                  new MaterialPageRoute(builder: (context) => new MyApp()),
                  (route) => route == null);
              // Navigator.pushAndRemoveUntil(context, new MaterialPageRoute(builder: (context) => new MyApp()), (route) => route == null);
              //Navigator.popAndPushNamed(context, "index");
              // Navigator.popAndPushNamed(context, routeName)
              //pref.setStringList('userinfo', data["info"]);
              // Navigator.of(context).popUntil(ModalRoute.withName("index"));
              //Navigator.pop(context);
              // Navigator.pushNamed(context, "index");
              //runApp(MyApp());
              Navigator.pushReplacementNamed(context, "index");
            } else if (data["code"].toString() == "-2") {
              showAlert(
                  data["info"]["failreason"], data["info"]["id"].toString());
            }
          }
        },
        params: map,
        errorCallback: (e) {
          print(e);
        });
  }

  showAlert(msg, id) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text(msg, style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            // Navigator.pop(context);

                            Navigator.pop(context);
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (_) {
                              return new AgentErrorPage(id);
                            }));
                          },
                          child: Center(
                              child: Text('去处理',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  @override
  Widget build(BuildContext context) {
    return
        // new MaterialApp(
        //   title: '登录',
        //   home:
        new Scaffold(
          backgroundColor: Colors.white,
      appBar: new AppBar(

       titleSpacing: 0,
        title: new Text(
          '登录',
          style: TextStyle(color: Colors.black,fontSize: Config.title_size,),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
      ),
      body: new ListView(
        children: <Widget>[
          new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              new Padding(
                  padding: new EdgeInsets.all(30.0),
                  child: new Image.asset(
                    'resource/images/user/logo2.png',
                    scale: 1.5,
                  )),
              new Padding(
                  padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 15.0),
                  child: new Container(
                      decoration: new BoxDecoration(
//背景
                        color: Colors.white,
                        //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
                        borderRadius: BorderRadius.all(Radius.circular(5.0)),
                        //设置四周边框
                        border: new Border.all(
                            width: 1, color: Color.fromRGBO(245, 245, 245, 1)),
                      ),
                      child: new Column(children: <Widget>[
                        new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                            child: new Container(
                              height: 52,
                              child: new Stack(
                                alignment: new Alignment(1.0, 1.0),
                                //statck
                                children: <Widget>[
                                  new Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceEvenly,
                                      children: [
                                        new Padding(
                                          padding: new EdgeInsets.fromLTRB(
                                              0.0, 0.0, 15.0, 0.0),
                                          child: new Image.asset(
                                            'resource/images/user/user2.png',
                                            width: 20.0,
                                            height: 20.0,
                                            fit: BoxFit.fill,
                                          ),
                                        ),
                                        new Expanded(
                                          child: new TextField(
                                            controller: _phonecontroller,
                                            keyboardType: TextInputType.number,
                                            decoration: new InputDecoration(
                                              border: InputBorder.none,
                                              hintText: '请输入用户名',
                                              hintStyle: TextStyle(fontSize: 16),
                                            ),
                                          ),
                                        ),
                                      ]),
                                  new IconButton(
                                    icon: new Icon(Icons.clear,
                                        color:
                                            Color.fromRGBO(245, 245, 245, 1)),
                                    onPressed: () {
                                      _phonecontroller.clear();
                                    },
                                  ),
                                ],
                              ),
                            )),
                        new Padding(
                          padding: new EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
                          child: Container(
                            height: 1,
                            color: Color.fromRGBO(245, 245, 245, 1),
                          ),
                        ),
                        new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                            child: new Container(
                              height: 52,
                              child: new Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: [
                                    new Padding(
                                      padding: new EdgeInsets.fromLTRB(
                                          0.0, 0.0, 15.0, 0.0),
                                      child: new Image.asset(
                                        'resource/images/user/user3.png',
                                        width: 20.0,
                                        height: 20.0,
                                        fit: BoxFit.fill,
                                      ),
                                    ),
                                    new Expanded(
                                      child: new TextField(
                                        controller: _pwdcontroller,
                                        decoration: new InputDecoration(
                                          border: InputBorder.none,
                                          hintText: '请输入密码',
                                          hintStyle: TextStyle(fontSize: 16),
                                          suffixIcon: new IconButton(
                                            icon: new Icon(Icons.clear,
                                                color: Color.fromRGBO(
                                                    235, 235, 235, 1)),
                                            onPressed: () {
                                              _pwdcontroller.clear();
                                            },
                                          ),
                                        ),
                                        obscureText: true,
                                      ),
                                    ),
                                  ]),
                            )),
                        // new Padding(
                        //   padding:
                        //       new EdgeInsets.fromLTRB(20.0, 1.0, 20.0, 40.0),
                        //   child: Container(
                        //     height: 1,
                        //     color: Color.fromRGBO(225, 225, 225, 1),
                        //   ),
                        // ),
                      ]))),
              Padding(
                  padding: new EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
                  child: new Container(
                    width: double.infinity,
                    child: new Card(
                      color: Colours.app_main,
                      // color: Color.fromRGBO(242, 185, 20, 1),
                      elevation: 1,
                      child: new FlatButton(
                        child: new Padding(
                          padding: new EdgeInsets.all(0.0),
                          child: new Text(
                            '登录',
                            style: new TextStyle(
                                color: Colors.white, fontSize: 16.0),
                          ),
                        ),
                        onPressed: () {
                          _checkPhone();
                          _checkPwd();
                          if (_phoneState && _pwdState) {
                            //_checkStr = '页面跳转下期见咯！';
                            login();
                          } else {
                            if (!_phoneState) {
                              _checkStr = '请输入11位手机号！';
                            } else if (!_pwdState) {
                              _checkStr = '请输入6-10位密码！';
                            }
                            Toast.show(_checkStr, context);
                          }
                        },
                      ),
                    ),
                  )),
              Padding(
                  padding: new EdgeInsets.fromLTRB(25, 10, 25, 10),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: new GestureDetector(
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text('注册账号'),
                          ),
                          onTap: () {
                            if (roles == "1") {
                              Navigator.pushNamed(context, "regist");
                            } else {
                              Navigator.pushNamed(context, "csapply");
                            }
                          },
                        ),
                        // child: new FlatButton(
                        //     onPressed: () {
                        //       Navigator.pushNamed(context, "regist");
                        //     },
                        //     child: Text('没账号？点击注册'))
                      ),
                      // Expanded(child: new Container(
                      //   width: 0,
                      //   color: Colors.red,
                      //   height:40

                      // )),
                      Expanded(
                        child: new GestureDetector(
                          child: Align(
                            alignment: Alignment.centerRight,
                            child: Text('忘记密码'),
                          ),
                          onTap: () {
                            Navigator.pushNamed(context, "forgetpass");
                          },
                        ),
                        // child: new FlatButton(
                        //     onPressed: () {
                        //       Navigator.pushNamed(context, "forgetpass");
                        //     },
                        //     child: Text(
                        //       '忘记密码',
                        //       textAlign: TextAlign.right,
                        //     )),
                      )
                    ],
                  ))
              // roles == "1"
              //     ? Padding(
              //         padding: new EdgeInsets.fromLTRB(15, 0, 15, 0),
              //         child: Center(
              //           child: new FlatButton(
              //             child: Text('没账号？点击注册'),
              //             onPressed: () {
              //               Navigator.pushNamed(context, "regist");
              //             },
              //           ),
              //         ),
              //       )
              //     : Text(''),
              // roles == "1"
              //     ? Padding(
              //         padding: new EdgeInsets.fromLTRB(15, 0, 15, 0),
              //         child: Center(
              //           child: new FlatButton(
              //             child: Text('忘记密码'),
              //             onPressed: () {
              //               Navigator.pushNamed(context, "forgetpass");
              //             },
              //           ),
              //         ),
              //       )
              //     : Text('')
            ],
          ),
        ],
      ),
    );
  }
}
